jQuery(function($){


    FastClick.attach(document.body);

    //点击获取验证码
    $('.get-code').on('click', APP.getCode);

    //登录|注册
    $('.member form[name=login]').on('submit', function(event){
        var  $this = $(this),
            type = $this.data('type'),
            phone = $('#account').val(),
            code = $('#code').val();
        event.preventDefault();

        if($this.data('ajax')){return  false }

        //手机号不通过
        if(!phone){
            APP.flashMessage('请输入手机号');
            return false
        }
        //手机号不通过
        if(!APP.phoneReg.test(phone)){
            APP.flashMessage('手机号格式不正确');
            return false
        }
        if(!code){
            APP.flashMessage('请输入验证码');
            return false
        }

        APP.showLoading();
        $this.data('ajax', true);

        $.ajax({
            url: jsCtx+'/h5/login/doLogin',
            method: 'post',
            dataType: 'json',
            data: $this.serialize()
        }).done(function(data){
            APP.closeLoading();
            $this.data('ajax', null);
            if(data.ret != 0){
                APP.flashMessage(data.desc);
                return false
            }
            if(type=='login'){
                APP.flashMessage( '登录成功');
                var source = data.data;
                if (source == 'web') {
                    window.location = jsCtx+'/h5/home/list?source=web';
                } else {
                    window.location = jsCtx+'/h5/home/index'
                }
            }else{
                APP.flashMessage( '注册成功');
                window.location = jsCtx+'/h5/login/reg2'
            }

        })
    });

    //注册第二步
    $('.member form[name=setting]').on('submit', function(event){
        var  $this = $(this),
            pass = $('#password').val(),
            pass2 = $('#password2').val(),
            name = $('#realname').val();

        event.preventDefault();

        if($this.data('ajax')){ return  false }

        //密码
        if(!pass){
            APP.flashMessage('请输入密码');
            return false
        }
        if(!pass2){
            APP.flashMessage('请再次输入密码');
            return false
        }
        if(pass !== pass2){
            APP.flashMessage('两次输入密码不一致');
            return false
        }
        if(!name){
            APP.flashMessage('请输入真实姓名');
            return false
        }

        APP.showLoading();
        $this.data('ajax', true);
        $.ajax({
            url: jsCtx+'/h5/login/doReg',
            method: 'post',
            dataType: 'json',
            data: $this.serialize()
        }).done(function(data){
            APP.closeLoading();
            $this.data('ajax', null);
            if(data.ret != 0){
                APP.flashMessage(data.desc);
                return false
            }
            $this.hide();
            $('.setting-success').show();
            window.location = jsCtx+'/h5/home/index'
        })
    });


    $('.order-submit-btn').on('click', function(){
        var startCityId = $('#startCityId').val();
        var startCityName = $('#startCityName').val();
        var startShopId = $('#startShopId').val();
        var startShopName = $('#startShopName').val();
        var startDate = $('#startDate').val();
        var endCityId = $('#endCityId').val();
        var endCityName = $('#endCityName').val();
        var endShopId = $('#endShopId').val();
        var endShopName = $('#endShopName').val();
        var endDate = $('#endDate').val();
        var carId = $('#carId').val();
        var carName = $('#carName').val();
        var carDescription = $('#carDescription').val();
        var price = $('#price').val();
        var days = $('#days').val();
        var total = $('#total').val();
        var totalSnapshot = $('#totalSnapshot').val();
        var bx1 = $('#bx1').val();
        var bx2 = $('#bx2').val();

        //优惠券信息
        var coupon = $('#coupon').find("option:selected");
        var couponGuid = coupon.val();
        var guid = coupon.data('guid');
        var subCount = coupon.data('subcount');
        var couponValue = coupon.data('couponvalue');
        var typeName = coupon.data('typename');

        //支付方式
        var payType = $('#payType').find("option:selected").val();

        var params = {"startCityId":startCityId,"startCityName":startCityName,"startShopId":startShopId,"startShopName":startShopName,
            "startDate":startDate,"endCityId":endCityId,"endCityName":endCityName,"endShopId":endShopId,"endShopName":endShopName,
            "endDate":endDate,"carId":carId,"carName":carName,"carDescription":carDescription,"price":price,"days":days,"total":total,
            "totalSnapshot":totalSnapshot,
            "couponGuid":couponGuid, "guid":guid, "subCount":subCount, "couponValue":couponValue, "typeName":typeName,
            "payType":payType,"bx1":bx1,"bx2":bx2};

        //确认储值支付
        if (payType == '1') {
            mobile.modal.confirm({
                title: '储值支付',
                content: '确认消费' + total +'元储值？',
                cancel: '取消',
                ok: '确认',
                cancelCb: function() {
                    return false;
                },
                callback: function() {
                    submitOrder(params)
                }
            });

        } else {
            submitOrder(params);
        }

    });

    //提交订单
    function submitOrder(params) {
        $.ajax({
            url: jsCtx+'/h5/home/submitOrder',
            method: 'post',
            dataType: 'json',
            data: params
        }).done(function(data){
            if (data.ret == 0) {//微信支付
                var form = '<form id="payForm" name="payForm" action="'+jsCtx+'/h5/home/tenpay" method="post">' +
                    '<input name="payOrderNo" type="hidden" value="' + data.data.payOrderNo + '" />' +
                    '<input name="payOrderMoney" type="hidden" value="' + data.data.payOrderMoney + '" />' +
                    '<input name="payOrderSubject" type="hidden" value="' + data.data.payOrderSubject + '" />' +
                    '<input name="openId" type="hidden" value="' + data.data.openId + '" />' +
                    '</form>';
                $('body').append(form);
                $('#payForm').submit();

            } else if (data.ret == 100) {//储值支付成功
                mobile.modal.alert({
                    content: '储值支付成功',
                    callback: function(){
                        window.location.href=jsCtx + '/h5/home/index'
                    }
                })
            } else if (data.ret == 99) {
                mobile.modal.alert({
                    content: '储值支付失败'
                })
            } else if (data.ret == 98) {
                mobile.modal.alert({
                    content: '储值余额不足'
                })
            } else if (data.ret == 2) {
                mobile.modal.alert({
                    content: '此车型车辆已被预定完，您可以选择其他车型',
                    callback: function(){
                        window.location.href=jsCtx + '/h5/home/index'
                    }
                })

            } else if (data.ret == 3) {
                mobile.modal.alert({content: data.msg});
            } else {
                mobile.modal.alert({
                    content: '订单提交失败'
                })
            }
        })
    }

    ////选择价格弹窗
    //$('body').on('click', '.car-item', function(){
    //    var data = $(this).data();
    //    var price = data.price;
    //    var htmls = '<div class="car-item flex">';
    //    console.log(price);
    //    $('.pop').removeClass('pop-close');
    //    htmls += '<div class="car-item-cover flex-none"><img src="'+data.cover+'"></div>' +
    //                '<div class="car-item-hd flex-auto">' +
    //                    '<div class="car-item-name">' +
    //                    '<a href="'+data.viewurl+'" target="_blank">'+data.name+'</a>' +
    //                    '<a href="'+data.viewurl+'" target="_blank" style="margin-left:7px;">预览</a>' +
    //                    '<a href="http://njylcx.m.yunhuiyuan.cn/Member/MemberGroupUpdate/?bid=69758e30-fead-e511-a18c-90b11c47b4db" target="_blank" style="margin-left:7px;color:red;">更多会员优惠</a>' +
    //                    '</div>' +
    //                    '<div class="car-item-type">'+data.type+'</div>' +
    //                '</div>' +
    //            '</div>';
    //
    //    $.each(price, function(){
    //        htmls += '<div class="price-option ' + (this.disabled ? 'disabled' : '') + ' flex" data-id= '+data.id+' data-price='+this.price+' data-name='+data.name+' data-type='+data.type+' data-cover='+data.cover+' >'
    //                +'<div class="price-option-type flex-auto">'+this.title+'</div>'
    //        +'<div class="price-option-val text-right flex-auto">￥<span>'+this.price+'</span>/日均</div>'
    //        +'   <div class="price-option-arrow ' + (this.disabled ? 'visible-hide' : '') + ' flex-none iconfont icon-gengduo"></div>'
    //        +'  </div>'
    //
    //    })
    //
    //    $('.car-selected').html(htmls + '</div>')
    //});
    //
    //
    //$('.pop-content').on('click', '.price-option:not(.disabled)', function(){
    //    var form = '<form id="jumpForm" name="jumpForm" action="'+jsCtx+'/h5/home/order" method="post">' +
    //                    '<input name="startCityId" type="hidden" value="' + $('#startCityId').val() + '" />' +
    //                    '<input name="startCityName" type="hidden" value="' + $('#startCityName').val() + '" />' +
    //                    '<input name="startShopId" type="hidden" value="' + $('#startShopId').val() + '" />' +
    //                    '<input name="startShopName" type="hidden" value="' + $('#startShopName').val() + '" />' +
    //                    '<input name="startDate" type="hidden" value="' + $('#startDate').val() + '" />' +
    //                    '<input name="endCityId" type="hidden" value="' + $('#endCityId').val() + '" />' +
    //                    '<input name="endCityName" type="hidden" value="' + $('#endCityName').val() + '" />' +
    //                    '<input name="endShopId" type="hidden" value="' + $('#endShopId').val() + '" />' +
    //                    '<input name="endShopName" type="hidden" value="' + $('#endShopName').val() + '" />' +
    //                    '<input name="endDate" type="hidden" value="' + $('#endDate').val() + '" />' +
    //                    '<input name="days" type="hidden" value="' + $('#days').val() + '" />' +
    //                    '<input name="price" type="hidden" value="' + $(this).data('price') + '" />' +
    //                    '<input name="carId" type="hidden" value="' + $(this).data('id') + '" />' +
    //                    '<input name="carName" type="hidden" value="' + $(this).data('name') + '" />' +
    //                    '<input name="carDescription" type="hidden" value="' + $(this).data('type') + '" />' +
    //                    '<input name="picUrl" type="hidden" value="' + $(this).data('cover') + '" />' +
    //               '</form>'
    //    $('body').append(form);
    //    $('#jumpForm').submit();
    //})

    //退改规则弹窗
    $('.show-book-rule').on('click', function(){
        $('.book-rule').css('height', $(window).height() * 0.6)
        $('.pop').removeClass('pop-close');
    });


    //点击pop关闭、点击里面内容不关闭 | 点击pop-ft
    $('.pop, .pop-ft').on('click', function(event){
        // event.preventDefault();
        $('.pop').addClass('pop-close');
    });
    $('.pop-inner').on('click', function(event){
        event.stopPropagation();
    });


});

var APP = APP || {};

APP.phoneReg = /^1\d{10}$/;

APP.showLoading =  function(){
    mobile.modal.modern({
        content: '<div class="loading">正在加载<\/div>'
    })
}

APP.closeLoading = function(){
    mobile.modal.close()
}

/**
 * 提示信息
 * @param msg 信息内容
 * @param classname 可选背景色 [danger(红色), success（绿色), warn(黑色)]
 */
APP.flashMessage =  function(msg, classname){
    return new Message({
        message: msg,
        delay: 1500,
        wrapClass: classname ?  classname:  'default'
    })
}

APP.getCode =  function(){
    var delay = 60,
        phone = $('#account').val(),
        $this = $(this);
    //正在获取
    if($(this).hasClass('disabled')){
        return false;
    }
    //手机号不通过
    if(!phone){
        APP.flashMessage('请输入手机号')
        return false
    }
    //手机号不通过
    if(!APP.phoneReg.test(phone)){
        APP.flashMessage('手机号格式不正确')
        return false
    }

    APP.showLoading();
    $(this).addClass('disabled');

    $.ajax({
        url: jsCtx+'/h5/login/sendCode',
        dataType: 'json',
        method: 'post',
        data: {
            phone: phone
        }
    }).done(function(data){
        APP.closeLoading();
        if(data.ret == 0){
            APP.flashMessage(data.msg);
            $this.removeClass('disabled');
            return false
        }
        $this.html( '剩余 ' + ( delay - 1) + ' s');

        var timer = setInterval(function(){
            delay = delay - 1;
            if(delay == 0){
                clearInterval(timer);
                $this.removeClass('disabled').html('获取验证码');
            }else{
                $this.html('剩余 ' +  delay + ' s');
            }
        }, 1000);
    })


}

function Message(options){
    var defaults = $.extend({
            width : 200,
            ease : 500,
            // delay : 500,
            wrapClass : "warn"
        }, options),
        self = this;

    this.defaults = defaults;

    this.message = $('<div  class="message message-'+ defaults.wrapClass +'"><div class="message-main">' + defaults.message + '</div></div>');

    $('body').append(this.message);

    //自动关闭窗口
    if(defaults.delay){
        defaults.timer = setTimeout(function(){
            self.close();
        }, defaults.delay);
    }
}

Message.prototype.close = function(){
    var self = this;
    self.message.animate({
        opacity : 0
    }, self.defaults.ease, function(){
        self.message.remove();
    });
};

var mobile =  function(){
    //弹出层
    var  modal = {
        mask : function(){
            return $("<div class=\"modal-mask\" \/>");
        }(),
        modal : function(){
            return $("<div class=\"modal-main\" \/>");
        }(),
        eventName : function(){
            //是否是手机浏览器返回对应的事件
            //click事件在手机上点击有阴影
            return navigator.userAgent.indexOf("Mobile") > - 1 ? "touchstart" : "click";
        }(),
        timer : null,
        alert : function(options){
            var  self = this, fw;
            options = $.extend({title: "", button: "确定"}, options);
            self.close();

            fw = self.fixWidth(options.width);

            self.modal.css({
                "width" : fw.width,
                "margin-left": fw.marginLeft
            }).append("<div class=\"modal-header\">" + options.title + "<\/div><div class=\"modal-content\">" + options.content + "<\/div><div class=\"modal-action\">" + options.button + "<\/div>");

            $('body').append(self.mask, self.modal);

            //bind event
            $(".modal-action").one(self.eventName, function(e){
                e.preventDefault();
                self.close();
                if(typeof options.callback === "function"){
                    options.callback.apply(null, options.args);
                }
            });
        },
        confirm : function(options){
            var  self = this, fw;
            options = $.extend({title: "", cancel: "返回", ok: "确定", args: []}, options);
            self.close();

            fw = self.fixWidth(options.width);

            self.modal.css({
                "width" : fw.width,
                "margin-left": fw.marginLeft
            }).addClass(options.wrapClass).append("<div class=\"modal-header\">" + options.title + "<\/div><div class=\"modal-content\">" + options.content + "<\/div><div class=\"modal-action modal-confirm-action\"><span class=\"modal-action-cancel\">" + options.cancel + "<\/span><span class=\"modal-action-ok\">" + options.ok + "<\/span><\/div>");

            $('body').append(self.mask, self.modal);

            //bind event
            $(".modal-action-cancel").one(self.eventName, function(e){
                e.preventDefault();
                self.close();
                if(typeof options.cancelCb === "function"){
                    options.cancelCb.apply(null, options.args);
                }
            });
            //bind event
            $(".modal-action-ok").one(this.eventName, function(e){
                e.preventDefault();
                self.close();
                if(typeof options.callback === "function"){
                    options.callback.apply(null, options.args);
                }
            });
        },
        modern : function(options){
            this.close();
            this.modal.css({
                "width" : "80px",
                "margin-left": "-40px",
            }).append("<div class=\"modal-modern modal-modern-" + options.type + "\">" + options.content + "<\/div>");

            $('body').append(this.mask, this.modal);

        },
        close : function(){
            var self = this;
            //console.log(this.timer);
            self.modal.empty().remove();
            self.mask.empty().remove();
        },
        //定位modal-main的位置
        fixWidth: function(w){
            var fw = {"width": "90%" , "marginLeft": "-45%"};

            if(typeof w === "number"){
                fw.width = w + "px";
                fw.marginLeft = "-" + Math.ceil(w / 2) + "px";
            }

            return fw;
        }
    };


    return {
        modal : modal
    };

}();


